﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Galaktika.BI.Silverlight.ClientApp.Web.DAL;
using System.IO;
using System.Security.Principal;
using Galaktika.BI.Silverlight.Services;
using System.Globalization;

namespace Galaktika.BI.Silverlight.ClientApp.Web
{
    public static class AppStorageFactory
    {
        static readonly string ClientXapItem = "client.xap";
        static readonly string UserSettingsXmlItem = "userSettings.xml";

        private static IAppSettingStorage CreateStorage()
        {
            return new Galaktika.BI.Silverlight.ClientApp.Web.IO.UserSettingsFileSystemStorage();
        }

        public static AppItemDescriptor[] GetItems(
            IEnumerable<AppItemDescriptor> cachedItems,
            IPrincipal currentPrincipal)
        {
            var res = new List<AppItemDescriptor>();
            //var notCreated = new Dictionary<string, AppItemDescriptor>();
            //notCreated.Add(ClientXapItem, new AppItemDescriptor() { Name = ClientXapItem, LastModified = DateTime.MinValue });
            //notCreated.Add(UserSettingsXmlItem, new AppItemDescriptor() { Name = UserSettingsXmlItem, LastModified = DateTime.MinValue });

            foreach (var cached in cachedItems)
            {
                if (cached.Name == ClientXapItem)
                {
                    res.Add(GetClientXap(cached));
                    //notCreated.Remove(ClientXapItem);
                }
                if (cached.Name == UserSettingsXmlItem)
                {
                    res.Add(GetUserSettingsXml(cached, currentPrincipal));
                    //notCreated.Remove(UserSettingsXmlItem);
                }
            }

            //foreach (var item in notCreated.Values)
            //{
            //    if (item.Name == ClientXapItem)
            //    {
            //        res.Add(GetClientXap(item));
            //    }
            //    if (item.Name == UserSettingsXmlItem)
            //    {
            //        res.Add(GetUserSettingsXml(item, currentPrincipal));
            //    }
            //}

            return res.ToArray();
        }

        public static void SetItems(IEnumerable<AppItemDescriptor> items, IPrincipal principal)
        {
            foreach (var item in items)
            {
                if (item.Name == UserSettingsXmlItem)
                {
                    SetUserSettingsXml(item, principal);
                }
            }
        }

        private static string ClientBinDir
        {
            get
            {
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ClientBin");
                if (!Directory.Exists(path))
                {
                    return null;
                }

                return path;
            }
        }

        private static string ReadFileContentAsBase64String(string path)
        {
            using (var fs = File.OpenRead(path))
            {
                byte[] buff = new byte[fs.Length];
                fs.Read(buff, 0, (int)fs.Length);

                return Convert.ToBase64String(buff);
            }
        }

        private static AppItemDescriptor GetClientXap(AppItemDescriptor xapItem)
        {
            var clientBin = ClientBinDir;
            if (!string.IsNullOrEmpty(clientBin))
            {
                var clientXap = Path.Combine(clientBin, ClientXapItem);
                if (File.Exists(clientXap))
                {
                    var modified = DateTimeHelper.GetLastWriteTime(clientXap);
                    if (modified > xapItem.LastModified)
                    {
                        return new AppItemDescriptor()
                        {
                            LastModified = modified,
                            Name = xapItem.Name,
                            Content = ReadFileContentAsBase64String(clientXap)
                        };
                    }
                }
            }

            return xapItem;
        }

        private static AppItemDescriptor GetUserSettingsXml(AppItemDescriptor settingsItem, IPrincipal currentPrincipal)
        {
            IAppSettingStorage storage = CreateStorage();
            var modified = storage.GetLastModifiedTime(currentPrincipal);
            if (modified > settingsItem.LastModified)
            {
                return new AppItemDescriptor()
                {
                    LastModified = modified,
                    Name = settingsItem.Name,
                    Content = storage.LoadSettings(currentPrincipal)
                };
            }

            return settingsItem;
        }

        private static void SetUserSettingsXml(AppItemDescriptor settingsItem, IPrincipal currentPrincipal)
        {
            var storage = CreateStorage();
            storage.SaveSettings(currentPrincipal, settingsItem.Content);
        }
    }
}
